{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "gXXhctqjgXO7"
   },
   "source": [
    "##### Copyright 2020 The Cirq Developers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "cellView": "form",
    "id": "z2RJVa8qgXou"
   },
   "outputs": [],
   "source": [
    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "# https://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EQvWLKKRgZR9"
   },
   "source": [
    "# Simulation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "EvZ_JecKga2p"
   },
   "source": [
    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://www.example.org/cirq/simulation\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on QuantumLib</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/simulation.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/simulation.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
    "  </td>\n",
    "  <td>\n",
    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/simulation.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
    "  </td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "bd9529db1c0b"
   },
   "outputs": [],
   "source": [
    "try:\n",
    "    import cirq\n",
    "except ImportError:\n",
    "    print(\"installing cirq...\")\n",
    "    !pip install --quiet cirq\n",
    "    print(\"installed cirq.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "4d599188f678"
   },
   "source": [
    "Cirq comes with built-in Python simulators for testing\n",
    "small circuits. The two main types of simulations that Cirq\n",
    "supports are pure state and mixed state. The pure state simulations\n",
    "are supported by ``cirq.Simulator`` and the mixed state\n",
    "simulators are supported by ``cirq.DensityMatrixSimulator``.\n",
    "\n",
    "The names *pure state simulator* and *mixed state\n",
    "simulators* refer to the fact that these simulations are\n",
    "for quantum circuits; including unitary, measurements, and noise\n",
    "that keeps the evolution in a pure state or a mixed state.\n",
    "In other words, there are some noisy evolutions\n",
    "that are supported by the pure state simulator as long as they\n",
    "preserve the purity of the state.\n",
    "\n",
    "Some external high-performance simulators also provide an interface\n",
    "to Cirq. These can sometimes provide results faster than Cirq's\n",
    "built-in simulators, especially when working with larger circuits.\n",
    "For details on these tools, see the\n",
    "[external simulators section](#external-simulators).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "de8b974f6597"
   },
   "source": [
    "## Introduction to pure state simulation\n",
    "\n",
    "Here is a simple circuit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "f3c82c1c12a6"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, 0): ───X^0.5───@───X^0.5───M('q0')───\n",
      "                   │\n",
      "(1, 0): ───X^0.5───@───X^0.5───M('q1')───\n"
     ]
    }
   ],
   "source": [
    "!pip install cirq --quiet\n",
    "import cirq\n",
    "\n",
    "q0 = cirq.GridQubit(0, 0)\n",
    "q1 = cirq.GridQubit(1, 0)\n",
    "\n",
    "def basic_circuit(meas=True):\n",
    "    sqrt_x = cirq.X**0.5\n",
    "    yield sqrt_x(q0), sqrt_x(q1)\n",
    "    yield cirq.CZ(q0, q1)\n",
    "    yield sqrt_x(q0), sqrt_x(q1)\n",
    "    if meas:\n",
    "        yield cirq.measure(q0, key='q0'), cirq.measure(q1, key='q1')\n",
    "\n",
    "circuit = cirq.Circuit()\n",
    "circuit.append(basic_circuit())\n",
    "\n",
    "print(circuit)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b4e74a859e3a"
   },
   "source": [
    "We can simulate this by creating a ``cirq.Simulator`` and\n",
    "passing the circuit into its ``run`` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "5422e0c06102"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q0=1\n",
      "q1=1\n"
     ]
    }
   ],
   "source": [
    "from cirq import Simulator\n",
    "simulator = Simulator()\n",
    "result = simulator.run(circuit)\n",
    "\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "31212f98dfa7"
   },
   "source": [
    "The method `run()` returns an ``Result``.  As you can see, the object `result` contains the result of any measurements for the simulation run.\n",
    "\n",
    "The actual measurement results depend on the seeding from `random` seed generator (`numpy`) . You can set this using ``numpy.random_seed``.\n",
    "\n",
    "Another run, can result in a different set of measurement results:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "e83b165ebf06"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q0=0\n",
      "q1=1\n"
     ]
    }
   ],
   "source": [
    "result = simulator.run(circuit)\n",
    "\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "b6847671058f"
   },
   "source": [
    "The simulator is designed to mimic what running a program\n",
    "on a quantum computer is actually like.  \n",
    "\n",
    "In particular, the ``run()`` methods (``run()`` and ``run_sweep()``) on the simulator do not give access to the wave function of the quantum computer (since one doesn't have access to this on the actual quantum\n",
    "hardware). Instead, the ``simulate()`` methods (``simulate()``,\n",
    "``simulate_sweep()``, ``simulate_moment_steps()``) should be used\n",
    "if one wants to debug the circuit and get access to the full\n",
    "wave function:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "e085289e0002"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.5+0.j  0. +0.5j 0. +0.5j 0.5+0.j ]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "circuit = cirq.Circuit()\n",
    "circuit.append(basic_circuit(False))    \n",
    "result = simulator.simulate(circuit, qubit_order=[q0, q1])\n",
    "\n",
    "print(np.around(result.final_state_vector, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "2f16e46f0c9a"
   },
   "source": [
    "Note that the simulator uses numpy's ``float32`` precision\n",
    "(which is ``complex64`` for complex numbers) by default,\n",
    "but that the simulator can take in a  `dtype` of `np.complex128`\n",
    "if higher precision is needed.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "028defe596bc"
   },
   "source": [
    "## Qubit and Amplitude Ordering\n",
    "\n",
    "The `qubit_order` argument to the simulator's `run()` method\n",
    "determines the ordering of some results, such as the\n",
    "amplitudes in the final wave function. The `qubit_order` argument is optional: when it is omitted, qubits are ordered\n",
    "ascending by their name (i.e., what their `__str__` method returns).\n",
    "\n",
    "The simplest `qubit_order` value you can provide is a list of\n",
    "the qubits in the desired ordered. Any qubits from the circuit\n",
    "that are not in the list will be ordered using the\n",
    "default `__str__` ordering, but come after qubits that are in\n",
    "the list. Be aware that all qubits in the list are included in\n",
    "the simulation, even if they are not operated on by the circuit.\n",
    "\n",
    "The mapping from the order of the qubits to the order of the\n",
    "amplitudes in the wave function can be tricky to understand.\n",
    "Basically, it is the same as the ordering used by `numpy.kron`:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "982a827446d3"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ 1  2 10 20]\n"
     ]
    }
   ],
   "source": [
    "outside = [1, 10]\n",
    "inside = [1, 2]\n",
    "print(np.kron(outside, inside))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "a36137200917"
   },
   "source": [
    "More concretely, `k`'th amplitude in the wave function\n",
    "will correspond to the `k`'th case that would be encountered\n",
    "when nesting loops over the possible values of each qubit.\n",
    "\n",
    "The first qubit's computational basis values are looped over\n",
    "in the outermost loop, the last qubit's computational basis\n",
    "values are looped over in the inner-most loop, etc.:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8141e8461313"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "amps[0] is for first=0, second=0\n",
      "amps[1] is for first=0, second=1\n",
      "amps[2] is for first=1, second=0\n",
      "amps[3] is for first=1, second=1\n"
     ]
    }
   ],
   "source": [
    "i = 0\n",
    "for first in [0, 1]:\n",
    "    for second in [0, 1]:\n",
    "        print('amps[{}] is for first={}, second={}'.format(i, first, second))\n",
    "        i += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "48c4d1acd296"
   },
   "source": [
    "We can check that this is in fact the ordering with a\n",
    "circuit that flips one qubit out of two:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "befc299bfd2a"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0. 0. 1. 0.]\n"
     ]
    }
   ],
   "source": [
    "q_stay = cirq.NamedQubit('q_stay')\n",
    "q_flip = cirq.NamedQubit('q_flip')\n",
    "c = cirq.Circuit(cirq.X(q_flip))\n",
    "\n",
    "# first qubit in order flipped\n",
    "result = simulator.simulate(c, qubit_order=[q_flip, q_stay])\n",
    "print(abs(result.final_state_vector).round(3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ca70c50a782f"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0. 1. 0. 0.]\n"
     ]
    }
   ],
   "source": [
    "# second qubit in order flipped\n",
    "result = simulator.simulate(c, qubit_order=[q_stay, q_flip])\n",
    "print(abs(result.final_state_vector).round(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "deda90b07995"
   },
   "source": [
    "## Stepping through a circuit\n",
    "\n",
    "When debugging, it is useful to not just see the end\n",
    "result of a circuit, but to inspect, or even modify, the\n",
    "state of the system at different steps in the circuit.  \n",
    "\n",
    "To support this, Cirq provides a method to return an iterator\n",
    "over a ``Moment`` by ``Moment`` simulation.  This method is named ``simulate_moment_steps``:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "68bc0a762450"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "state at step 0: [0. +0.5j 0.5+0.j  0.5+0.j  0. -0.5j]\n",
      "state at step 1: [0. +0.5j 0.5+0.j  0.5+0.j  0. +0.5j]\n",
      "state at step 2: [0.5+0.j  0. +0.5j 0. +0.5j 0.5+0.j ]\n",
      "state at step 3: [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n"
     ]
    }
   ],
   "source": [
    "circuit = cirq.Circuit()\n",
    "circuit.append(basic_circuit())    \n",
    "for i, step in enumerate(simulator.simulate_moment_steps(circuit)):\n",
    "    print('state at step %d: %s' % (i, np.around(step.state_vector(), 3)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ef682175a07b"
   },
   "source": [
    "The object returned by the ``moment_steps`` iterator is a\n",
    "``StepResult``. This object has the state along with any\n",
    "measurements that occurred **during** that step (so does\n",
    "not include measurement results from previous ``Moments``).\n",
    "\n",
    "In addition, the ``StepResult`` contains ``set_state()``,\n",
    "which  can be used to set the ``state``. One can pass a valid\n",
    "full state to this method by passing a numpy array. Or,\n",
    "alternatively, one can pass an integer, and then the state\n",
    "will be set lie entirely in the computation basis state\n",
    "for the binary expansion of the passed integer."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "p_IOhhsWgnTg"
   },
   "source": [
    "## Parameterized values and studies\n",
    "\n",
    "In addition to circuit gates with fixed values, Cirq also\n",
    "supports gates which can have ``Symbol`` value (see\n",
    "[Gates](gates.ipynb)). These are values that can be resolved\n",
    "at *run-time*. \n",
    "\n",
    "For simulators, these values are resolved by\n",
    "providing a ``ParamResolver``.  A ``ParamResolver`` provides\n",
    "a map from the ``Symbol``'s name to its assigned value."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1b5c6f4438ef"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
      "[ 0.6 +0.6j   0.25-0.25j  0.25-0.25j -0.1 -0.1j ]\n",
      "[0. +0.5j 0.5+0.j  0.5+0.j  0. -0.5j]\n",
      "[-0.1 +0.1j   0.25+0.25j  0.25+0.25j  0.6 -0.6j ]\n",
      "[0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n"
     ]
    }
   ],
   "source": [
    "import sympy\n",
    "rot_w_gate = cirq.X**sympy.Symbol('x')\n",
    "circuit = cirq.Circuit()\n",
    "circuit.append([rot_w_gate(q0), rot_w_gate(q1)])\n",
    "for y in range(5):\n",
    "    resolver = cirq.ParamResolver({'x': y / 4.0})\n",
    "    result = simulator.simulate(circuit, resolver)\n",
    "    print(np.round(result.final_state_vector, 2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "10617793bfd2"
   },
   "source": [
    "Here we see that the ``Symbol`` is used in two gates, and then the resolver provides this value at run time.\n",
    "\n",
    "Parameterized values are most useful in defining what we call a\n",
    "``sweep``.  A ``sweep`` is a sequence of trials, where each\n",
    "trial is a run with a particular set of parameter values.\n",
    "\n",
    "Running a ``sweep`` returns a ``Result`` for each set of fixed parameter values and repetitions.  \n",
    "\n",
    "For instance:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ccc88952ba49"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "q0=00\n",
      "q1=00\n",
      "q0=00\n",
      "q1=11\n",
      "q0=11\n",
      "q1=11\n"
     ]
    }
   ],
   "source": [
    "resolvers = [cirq.ParamResolver({'x': y / 2.0}) for y in range(3)]\n",
    "circuit = cirq.Circuit()\n",
    "circuit.append([rot_w_gate(q0), rot_w_gate(q1)])\n",
    "circuit.append([cirq.measure(q0, key='q0'), cirq.measure(q1, key='q1')])\n",
    "results = simulator.run_sweep(program=circuit,\n",
    "                              params=resolvers,\n",
    "                              repetitions=2)\n",
    "for result in results:\n",
    "    print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "5ca5f417ca71"
   },
   "source": [
    "Above we see that assigning different values to gate parameters yields\n",
    "different results for each trial in the sweep, and that each trial is repeated\n",
    "``repetitions`` times."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "d449810f2cad"
   },
   "source": [
    "## Mixed state simulations\n",
    "\n",
    "In addition to pure state simulation, Cirq also supports\n",
    "simulation of mixed states. \n",
    "\n",
    "Even though this simulator is not as efficient as the pure state simulators, they allow for a larger class of noisy circuits to be run as well as keeping track of the simulation's density matrix. This fact can allow for more exact simulations (for example,\n",
    "the pure state simulator's Monte Carlo simulation only\n",
    "allows sampling from the density matrix, not explicitly giving\n",
    "the entries of the density matrix like the mixed state simulator\n",
    "can do). \n",
    "\n",
    "Mixed state simulation is supported by the\n",
    "``cirq.DensityMatrixSimulator`` class.\n",
    "\n",
    "Here is a simple example of simulating a channel using the\n",
    "mixed state simulator:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "9bc8775b8ef9"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Counter({0: 64, 1: 36})\n"
     ]
    }
   ],
   "source": [
    "q = cirq.NamedQubit('a')\n",
    "circuit = cirq.Circuit(cirq.H(q), cirq.amplitude_damp(0.2)(q), cirq.measure(q))\n",
    "simulator = cirq.DensityMatrixSimulator()\n",
    "result = simulator.run(circuit, repetitions=100)\n",
    "print(result.histogram(key='a'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "164ccf2b7d71"
   },
   "source": [
    "We create a state in an equal superposition of 0 and 1,\n",
    "then apply amplitude damping which takes 1 to 0 with\n",
    "something like a probability of 0.2. \n",
    "\n",
    "We see that instead of about 50 percent of the timing being in 0, about 20 percent of the 1 has been converted into 0, so we end up with total\n",
    "around 60 percent in the 0 state.\n",
    "\n",
    "Like the pure state simulators, the mixed state simulator\n",
    "supports ``run()`` and ``run_sweeps()`` methods. \n",
    "\n",
    "The ``cirq.DensityMatrixSimulator`` also supports getting access\n",
    "to the density matrix of the circuit at the end of simulating\n",
    "the circuit, or when stepping through the circuit.  These are\n",
    "done by the ``simulate()`` and ``simulate_sweep()`` methods, or,\n",
    "for stepping through the circuit, via the ``simulate_moment_steps``\n",
    "method.   For example, we can simulate creating an equal\n",
    "superposition followed by an amplitude damping channel with a\n",
    "gamma of 0.2 by:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "c66bc5094882"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[0.6  +0.j 0.447+0.j]\n",
      " [0.447+0.j 0.4  +0.j]]\n"
     ]
    }
   ],
   "source": [
    "q = cirq.NamedQubit('a')\n",
    "circuit = cirq.Circuit(cirq.H(q), cirq.amplitude_damp(0.2)(q))\n",
    "simulator = cirq.DensityMatrixSimulator()\n",
    "result = simulator.simulate(circuit)\n",
    "print(np.around(result.final_density_matrix, 3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "ce9b181d8c72"
   },
   "source": [
    "We see that we have access to the density matrix at the\n",
    "end of the simulation via ``final_density_matrix``."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "3e15de52ca5f"
   },
   "source": [
    "## External simulators\n",
    "\n",
    "There are a few high-performance circuit simulators which\n",
    "provide an interface for simulating Cirq ``Circuit``s.\n",
    "These projects are listed below, along with their PyPI package\n",
    "name and a description of simulator methods that they support.\n",
    "\n",
    "**Note:** In general, these simulators are optimized for\n",
    "specific use cases. Before choosing a simulator, make sure it\n",
    "supports the behavior that you need!\n",
    "\n",
    "| Project name | PyPI package | Description |\n",
    "| --- | --- | --- |\n",
    "| [qsim](https://github.com/quantumlib/qsim) | qsimcirq | Implements ``SimulatesAmplitudes`` and ``SimulatesFinalState``. Recommended for deep circuits with up to 30 qubits (consumes 8GB RAM). Larger circuits are possible, but RAM usage doubles with each additional qubit. |\n",
    "| [qsimh](https://github.com/quantumlib/qsim/blob/master/qsimcirq/qsimh_simulator.py) | qsimcirq | Implements ``SimulatesAmplitudes``. Intended for heavy parallelization across several computers; Cirq users should generally prefer qsim. |\n",
    "| [qFlex](https://github.com/ngnrsaa/qflex) | qflexcirq | Implements ``SimulatesAmplitudes``. Recommended for shallow / low-entanglement circuits with more than 30 qubits. RAM usage is highly dependent on the number of two-qubit gates in the circuit. |\n",
    "| [quimb](https://quimb.readthedocs.io/en/latest/) | quimb | Cirq-to-quimb translation layer provided in `contrib/quimb`. In addition to circuit simulation, this allows the use of quimb circuit-analysis tools on Cirq circuits. |\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "name": "simulation.ipynb",
   "toc_visible": true
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
